package com.xuerhua.yxt.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.enums.DictDataCode;
import com.xuerhua.yxt.common.enums.InterestCourseStatus;
import com.xuerhua.yxt.common.enums.RelationType;
import com.xuerhua.yxt.dao.AttachmentListMapper;
import com.xuerhua.yxt.dao.InterestCourseInfoMapper;
import com.xuerhua.yxt.dao.InterestCourseStudentSignMapper;
import com.xuerhua.yxt.dao.ParentInfoMapper;
import com.xuerhua.yxt.dao.ReqInterestCourseChangeMapper;
import com.xuerhua.yxt.dao.SchoolWechatTemplateMapper;
import com.xuerhua.yxt.dao.TeacherInfoMapper;
import com.xuerhua.yxt.model.AttachmentList;
import com.xuerhua.yxt.model.InterestCourseInfo;
import com.xuerhua.yxt.model.InterestCourseStudentSign;
import com.xuerhua.yxt.model.ParentInfo;
import com.xuerhua.yxt.model.ReqInterestCourseChange;
import com.xuerhua.yxt.model.SchoolInfo;
import com.xuerhua.yxt.model.TeacherInfo;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.AttachRelationReqVO;
import com.xuerhua.yxt.reqVo.BaseQueryVO;
import com.xuerhua.yxt.reqVo.InterestCourseQueryVO;
import com.xuerhua.yxt.reqVo.InterestCourseReqVO;
import com.xuerhua.yxt.reqVo.ReqInterestCourseQueryVO;
import com.xuerhua.yxt.service.IInterestCourseInfoService;
import com.xuerhua.yxt.service.ISchoolInfoService;
import com.xuerhua.yxt.view.InterestCourseStudentSignView;
import com.xuerhua.yxt.view.InterestCourseView;
import com.xuerhua.yxt.view.ParentRelStudentView;
import com.xuerhua.yxt.view.ReqInterestCourseView;
import com.xuerhua.yxt.wechat.utils.TemplateUtil;

@Service("interestCourseInfoService")
public class InterestCourseInfoServiceImpl implements IInterestCourseInfoService {

	@Autowired
	private InterestCourseInfoMapper interestCourseInfoMapper;
	@Autowired
	private AttachmentListMapper attachmentListMapper;
	@Autowired
	private InterestCourseStudentSignMapper interestCourseStudentSignMapper;
	@Autowired
	private ReqInterestCourseChangeMapper reqInterestCourseChangeMapper;
	@Autowired
	private ParentInfoMapper parentInfoMapper;
	@Autowired
	private TeacherInfoMapper teacherInfoMapper;
	@Autowired
	private ISchoolInfoService schoolInfoService;
	@Autowired
	private SchoolWechatTemplateMapper schoolWechatTemplateMapper;
	
	@Override
	public int insertSelective(InterestCourseInfo record) {
		return interestCourseInfoMapper.insertSelective(record);
	}

	@Override
	public InterestCourseInfo selectByPrimaryKey(Integer id) {
		return interestCourseInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(InterestCourseInfo record) {
		return interestCourseInfoMapper.updateByPrimaryKeySelective(record);
	}
	
	@Override
	public List<InterestCourseView> selectViewList(BaseQueryVO vo) {
		return interestCourseInfoMapper.selectViewList(vo);
	}
	@Override
	public List<InterestCourseView> selectViewListForClass(BaseQueryVO vo) {
		List<InterestCourseView> list = interestCourseInfoMapper.selectViewList(vo);
		String grade = vo.getFinishYear() + 7 - vo.getGrade() + "";
		String gradeClass =  grade + (vo.getClazz() < 10 ? ("0" + vo.getClazz()) : vo.getClass());
		List<InterestCourseView> resultList = new ArrayList<>();
		for(InterestCourseView view : list) {
			if(StringUtils.isBlank(view.getTeachingObject()) || 
				(StringUtils.isNotBlank(vo.getKey()) && 
				view.getId().intValue() == Integer.valueOf(vo.getKey()).intValue())) continue;
			String grades = "";
			int idx = view.getTeachingObject().indexOf("年级");
			if(idx != -1) {
				grades = view.getTeachingObject().substring(0, idx);
			}
			if(view.getTeachingObject().indexOf(gradeClass) != -1 || grades.indexOf(grade) != -1) {
				resultList.add(view);
			}
		}
		return resultList;
	}
	@Override
	public List<InterestCourseInfo> selectList(BaseQueryVO vo) {
		return interestCourseInfoMapper.selectList(vo);
	}
	@Override
	public InterestCourseView selectViewById(BaseQueryVO vo) {
		InterestCourseView view = interestCourseInfoMapper.selectViewById(vo);
		if(StringUtils.isNotBlank(view.getMainImg())) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", RelationType.INTEREST_COURSE.getCode());
			map.put("objId", vo.getId());
			List<AttachmentList> attachmentList = attachmentListMapper.queryAttachmentListByRelationId(map);
			view.setAttachList(attachmentList);
		}
		return view;
	}

	@Override
	public int addAndUpdate(InterestCourseReqVO vo) {
		if(vo.getId() == null) {
			interestCourseInfoMapper.insertSelective(vo);
			if(StringUtils.isNotBlank(vo.getAttachIds())) {
				AttachRelationReqVO attachReqVO = new AttachRelationReqVO();
				String[] array = vo.getAttachIds().split(",");
				attachReqVO.setRelationId(Long.valueOf(vo.getId()));
				attachReqVO.setAttachIds(array);
				attachmentListMapper.updateRelationIdByIds(attachReqVO);
			}
		}else {
			interestCourseInfoMapper.updateByPrimaryKeySelective(vo);
			AttachRelationReqVO attachReqVO = new AttachRelationReqVO();
			attachReqVO.setRelationId(Long.valueOf(vo.getId()));
			if(StringUtils.isNotBlank(vo.getAttachIds())) {
				String[] array = vo.getAttachIds().split(",");
				attachReqVO.setAttachIds(array);
			}else {
				String[] array = {"0"};
				attachReqVO.setAttachIds(array);
			}
			attachmentListMapper.updateInvaildForRevByIds(attachReqVO);
			if(StringUtils.isNotBlank(vo.getAttachIds())) {
				attachmentListMapper.updateRelationIdByIds(attachReqVO);
			}
		}
		return 1;
	}

	@Override
	public List<InterestCourseStudentSignView> selectSignedListForClass(InterestCourseQueryVO vo) {
		return interestCourseStudentSignMapper.selectSignedListForClass(vo);
	}

	@Override
	public List<InterestCourseStudentSignView> selectNoSignListForClass(InterestCourseQueryVO vo) {
		return interestCourseStudentSignMapper.selectNoSignListForClass(vo);
	}

	@Override
	public InterestCourseStudentSignView selectSignedCourseForStudent(InterestCourseQueryVO vo) {
		return interestCourseStudentSignMapper.selectSignedCourseForStudent(vo);
	}

	@Override
	public int insertSign(InterestCourseStudentSign record) {
		return interestCourseStudentSignMapper.insertSelective(record);
	}

	@Override
	public int updateChangeSign(InterestCourseStudentSign record) {
		return interestCourseStudentSignMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int addChangeCourseReqByParent(ReqInterestCourseChange record) {
		return reqInterestCourseChangeMapper.insertSelective(record);
	}
	
	@Override
	public int addChangeCourseReqByTeacher(ReqInterestCourseChange record) {
		reqInterestCourseChangeMapper.insertSelective(record);
		int count =  interestCourseStudentSignMapper.updateStudentSignCourse(record);
		new Thread(new MemberChangeExecutor(2, record));
		return count;
	}

	@Override
	public List<ReqInterestCourseView> selectPendingReqList(ReqInterestCourseQueryVO vo) {
		return reqInterestCourseChangeMapper.selectPendingReqList(vo);
	}

	@Override
	public List<ReqInterestCourseView> selectAuditedReqList(Page<ReqInterestCourseView> page) {
		return reqInterestCourseChangeMapper.selectAuditedReqList(page);
	}

	@Override
	public List<InterestCourseStudentSignView> selectSignListForParent(InterestCourseQueryVO vo) {
		return interestCourseStudentSignMapper.selectSignListForParent(vo);
	}

	@Override
	public boolean isFullForCourseId(BaseQueryVO vo) {
		InterestCourseInfo courseInfo = interestCourseInfoMapper.selectByPrimaryKey(vo.getId());
		if(courseInfo.getLimitNum() != null) {
			int count = interestCourseStudentSignMapper.seletCountByCourseId(vo);
			if(count >= courseInfo.getLimitNum().intValue()) {
				return true;
			}
		}
		return false;
	}

	@Override
	public int updateStudentSignCourse(ReqInterestCourseChange record) {
		return interestCourseStudentSignMapper.updateStudentSignCourse(record);
	}

	@Override
	public List<ReqInterestCourseView> selectListForParent(ReqInterestCourseQueryVO vo) {
		return reqInterestCourseChangeMapper.selectListForParent(vo);
	}

	@Override
	public int selectCountForStudent(ReqInterestCourseQueryVO vo) {
		return reqInterestCourseChangeMapper.selectCountForStudent(vo);
	}

	@Override
	public boolean isTeachingTeacher(Integer teacherId) {
		int count = interestCourseInfoMapper.selectCountByTeacherId(teacherId);
		return count > 0 ? true : false;
	}

	@Override
	public List<InterestCourseView> selectViewForTeaching(BaseQueryVO vo) {
		return interestCourseInfoMapper.selectViewForTeaching(vo);
	}

	@Override
	public List<InterestCourseStudentSignView> selectSignListForTeachingByCourseId(InterestCourseQueryVO vo) {
		return interestCourseStudentSignMapper.selectSignListForTeachingByCourseId(vo);
	}

	@Override
	public void updateAuditByClassTeacher(ReqInterestCourseChange record) {
		record.setUpdateTime(new Date());
		reqInterestCourseChangeMapper.updateByPrimaryKeySelective(record);
		if(InterestCourseStatus.AUDIT_SUCCESS.getCode().equals(record.getStatus())) {
			ReqInterestCourseChange reqInfo = reqInterestCourseChangeMapper.selectByPrimaryKey(record.getId());
			InterestCourseStudentSign sign = new InterestCourseStudentSign();
			sign.setTermId(reqInfo.getTermId());
			sign.setStudentId(reqInfo.getStudentId());
			sign.setCourseId(reqInfo.getOldCourseId());
			InterestCourseStudentSign result = interestCourseStudentSignMapper.selectByParam(sign);
			result.setCourseId(reqInfo.getNewCourseId());
			interestCourseStudentSignMapper.updateByPrimaryKeySelective(result);
		}
		new Thread(new MemberChangeExecutor(1, record)).start();
	}
	
	class MemberChangeExecutor implements Runnable {
		
		private ReqInterestCourseChange record;
		
		//操作人 1家长 2老师
		private Integer operator;
		
		public MemberChangeExecutor(Integer operator, ReqInterestCourseChange record) {
			this.operator = operator;
			this.record = record;
		}

		@Override
		public void run() {
			try { 
				ReqInterestCourseChange reqInfo = reqInterestCourseChangeMapper.selectByPrimaryKey(record.getId());
				SchoolInfo school = schoolInfoService.queryInitWechatBySchoolId(record.getSchoolId());
				if(operator == 1) {
					String templateId = schoolWechatTemplateMapper.selectTemplateKey(
							school.getId(), DictDataCode.SCHOOL_PARENT_RELATION.getCode());
					String reqUrl = school.getDomainUrl() + Const.STUDENT_ROLE + 
							MenuConst.INTEREST_COURSE + "?sid=" + reqInfo.getStudentId();
					List<ParentRelStudentView> parentList = parentInfoMapper.selectParentListByStudentId(reqInfo.getStudentId());
					for(ParentInfo parent : parentList) {
						school = schoolInfoService.refreshInitWechat(school);
						TemplateUtil.courseChangeSend(school,parent.getOpenid(), templateId, reqInfo.getStudentName(), reqUrl);
					}
				}
				if(reqInfo.getStatus().equals(InterestCourseStatus.AUDIT_SUCCESS.getCode())) {
					String templateId = schoolWechatTemplateMapper.selectTemplateKey(
							school.getId(), DictDataCode.COURSE_MEMBER_CHANGE.getCode());
					String reqUrl = school.getDomainUrl() + Const.TEACHER_ROLE + 
							MenuConst.INTEREST_COURSE + "/teachingCourse";
					List<TeacherInfo> teacherList = teacherInfoMapper.selectListForCourseId(reqInfo.getOldCourseId());
					BaseQueryVO vo = new BaseQueryVO();
					vo.setTermId(reqInfo.getTermId());
					vo.setId(reqInfo.getOldCourseId());
					int memberCount = interestCourseStudentSignMapper.seletCountByCourseId(vo);
					InterestCourseInfo courseInfo = interestCourseInfoMapper.selectByPrimaryKey(reqInfo.getOldCourseId());
					for(TeacherInfo teacher : teacherList) {
						school = schoolInfoService.refreshInitWechat(school);
						TemplateUtil.courseMemberChangeSend(school,teacher.getOpenid(), templateId, teacher.getName(), 
								"无", reqInfo.getStudentName(), memberCount, courseInfo.getCourseName(), reqUrl);
					}
					List<TeacherInfo> teacherList1 = teacherInfoMapper.selectListForCourseId(reqInfo.getNewCourseId());
					vo.setId(reqInfo.getNewCourseId());
					memberCount = interestCourseStudentSignMapper.seletCountByCourseId(vo);
					courseInfo = interestCourseInfoMapper.selectByPrimaryKey(reqInfo.getNewCourseId());
					for(TeacherInfo teacher : teacherList1) {
						school = schoolInfoService.refreshInitWechat(school);
						TemplateUtil.courseMemberChangeSend(school,teacher.getOpenid(), templateId, teacher.getName(), 
								reqInfo.getStudentName(), "无", memberCount, courseInfo.getCourseName(), reqUrl);
					}
				}
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        }
		}
	}
}
